package com.fzkj.jdkfeature.java8.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * java8 stream 测试
 */
public class StreamTest {

    public static void main(String[] args) {
//        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//        List<Integer> numbers = List.of(3, 2, 2, 3, 7, 3);
//
//        IntStream intStream = numbers.stream().mapToInt((x) -> x);
//        IntSummaryStatistics stats = intStream.summaryStatistics();
//
//        System.out.println("列表中最大的数 : " + stats.getMax());
//        System.out.println("列表中最小的数 : " + stats.getMin());
//        System.out.println("所有数之和 : " + stats.getSum());
//        System.out.println("平均数 : " + stats.getAverage());
//
//        // List使用mapToInt
//        List<Integer> list = List.of(1, 2, 3, 4);
//        // 改造Integer流
//        list.stream().mapToInt(t -> t*2).forEach(System.out::println);
//        // 对Integer流内元素进行计算，除了sum()还有许多操作
//        System.out.println(list.stream().mapToInt(t -> t*2).sum());


        List<Optional<String>> list = Arrays.asList (
                Optional.empty(),
                Optional.of("A"),
                Optional.empty(),
                Optional.of("B"));

        //filter the list based to print non-empty values

        //if optional is non-empty, get the value in stream, otherwise return empty
        List<String> filteredList = list.stream()
                .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
                .collect(Collectors.toList());

        //Optional::stream method will return a stream of either one
        //or zero element if data is present or not.
        List<String> filteredListJava9 = list.stream()
                .flatMap(Optional::stream)
                .collect(Collectors.toList());

        System.out.println(filteredList);
        System.out.println(filteredListJava9);


        Optional<Integer> integer = Optional.of(999);
        System.out.println(integer.stream().collect(Collectors.toList()));

        System.out.println("---------------------------------------------");

        Optional<Integer> optional = Optional.of(1);

        optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
                System.out.println("Not Present."));

        optional = Optional.empty();

        optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
                System.out.println("Not Present."));
    }

}
